package com.jeesite.modules.task.feedback.service;

import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.backlog.service.DcSupBacklogService;
import com.jeesite.modules.msg.entity.content.PcMsgContent;
import com.jeesite.modules.msg.utils.MsgPushUtils;
import com.jeesite.modules.sys.dao.EmpUserDao;
import com.jeesite.modules.sys.entity.*;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.RoleUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.dao.DcSupTaskActionDao;
import com.jeesite.modules.task.action.entity.DcSupTaskAction;
import com.jeesite.modules.task.deploy.entity.OfficeUser;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoService;
import com.jeesite.modules.task.feedback.dao.DcSupTaskFeedbackDao;
import com.jeesite.modules.task.feedback.entity.DcSupTaskFeedback;
import com.jeesite.modules.utils.OfficeUtil;
import com.jeesite.modules.yzw.entity.MsgDetail;
import com.jeesite.modules.yzw.service.LehandYzwPushTask;
import com.jeesite.modules.yzw.service.SmsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service(value = "dcSupTaskSendFeedbackMsgService")
@Slf4j
public class DcSupTaskSendFeedbackMsgService extends CrudService<DcSupTaskFeedbackDao, DcSupTaskFeedback> {
    @Autowired
    private DcSupTaskFeedbackDao dcSupTaskFeedbackDao;

    @Autowired
    private EmpUserService empUserService;

    @Autowired
    private SmsClient smsClient;
    @Autowired
    private DcSupTaskActionDao dcSupTaskActionDao;
    @Autowired
    private DcSupBacklogService dcSupBacklogService;

    /**
     * 反馈截止前一天 通知消息到yzw
     */
    public void sendYzwFeedbackMessage() {
        String config = Global.getConfig("sys.note.switch", "0");
        if (!"2".equals(config)){
            log.info("停止发送反馈提醒，短信功能未开启！");
            return;
        }
        log.info("开始执行反馈提醒任务");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1);
        //当前日期加一天时间
        String add1DayDate = sf.format(c.getTime());
        c.add(Calendar.DAY_OF_MONTH, 1);
        //当前日期加两天时间
        String add2DayDate = sf.format(c.getTime());
        log.info("数据查询范围：{}，{}", add1DayDate, add2DayDate);
        //查询将来一天数据
        List<DcSupTaskFeedback> feedbacks = dcSupTaskFeedbackDao.findListWithReminder(add1DayDate, add2DayDate);
        log.info("数据长度：{}", feedbacks.size());
        List<Map<String,String>> msgDetails = new ArrayList<>();
        for (DcSupTaskFeedback feedback : feedbacks) {
            if ("1".equals(feedback.getTransferFlag())) {
                User user = UserUtils.get(feedback.getTransferOrgCode());
                if (user != null) {
                    msgDetails.add(createMsgDetail(feedback, user.getUserCode()));
                }
            } else {
                //未转发
                List<EmpUser> userList = findEmpUser(feedback.getLeaderOrgCode());
                for (EmpUser user : userList) {
                    msgDetails.add(createMsgDetail(feedback, user.getPhone()));
                }
            }
        }
        if (CollectionUtils.isEmpty(msgDetails)){
            return;
        }

        smsClient.sendSmsList(msgDetails);
        log.info("任务提交结束！");
    }

    public void sendYzwFeedbackMessageNew() {
        //获取明天的年月日
        String time = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//设置格式
        Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, +1); //当前时间加去一天，即一天后的时间
        String date1 = simpleDateFormat.format(calendar.getTime());
        //根据明天的年月日查出未反馈和草稿的feedback数据,整合成id以逗号分割
        String actionId = dao.getFeedbackListRemind(date1);
        if(!StringUtils.isBlank(actionId)){
            //放到set中去重
            HashSet<String> hashSet = new HashSet(Arrays.asList(actionId.split(",")));
            //去重后放到list中待处理
            List<String> actionIdList = new ArrayList<>(hashSet);
            //循环发送消息
            for (int i = 0; i < actionIdList.size(); i++) {
                //根据去重后的actionId查询出action的数据
                DcSupTaskAction action = dao.getActionListById(actionIdList.get(i));
                //判断是否转办
                if(StringUtils.isNotBlank(action.getTransferOrgCode())){
                    //发送站内信给转办人
                    PcMsgContent msg = new PcMsgContent();
                    msg.setTitle("提示信息");
                    msg.addButton("任务待办", "/a/action/dcSupTaskAction/noCompleteView");
                    msg.setContent("您有一条任务名为：'"+action.getTaskTitle()+"'的任务反馈即将逾期,请及时反馈!");
                    MsgPushUtils.push(msg, action.getTaskId() + "_" + action.getLeaderOrgCode(), "feedback_msg", action.getTransferOrgCode());
                    dcSupBacklogService.add("督查督办","定时任务推送","反馈逾期提醒","提示信息"
                            ,"您有一条任务名为：'"+action.getTaskTitle()+"'的任务反馈即将逾期,请及时反馈!"
                            ,"/a/action/dcSupTaskAction/noCompleteView",action.getLeaderOrgCode()
                            ,action.getId(),"task_yuqi",action.getTransferOrgCode()
                            ,action.getTaskId(),action.getId());
                }else if(action.getTaskReceiveTime()==null){

                }else{
                    //发送站内信给收文员
                    DcSupTaskAction actionQuery = new DcSupTaskAction();
                    actionQuery.setId(actionIdList.get(i));
                    DcSupTaskAction dcSupTaskAction = dcSupTaskActionDao.get(actionQuery);
                    List<OfficeUser> userByOrg = dcSupTaskActionDao.getUserByOrg("OTSTRANSFER", dcSupTaskAction.getLeaderOrgCode());
                    for (OfficeUser user : userByOrg) {
                        PcMsgContent msg = new PcMsgContent();
                        msg.setTitle("提示信息");
                        msg.setContent("您有一条任务名为：'"+action.getTaskTitle()+"'的任务反馈即将逾期,请及时反馈!");
                        if(action.getTaskReceiveTime()==null){//未接收
                            msg.addButton("任务接收", "/a/audit/taskReceive/list");
                        }else{
                            msg.addButton("任务反馈", "/a/audit/taskReceive/list1");
                        }
                        MsgPushUtils.push(msg, action.getTaskId() + "_" + actionIdList.get(i), "feedback_msg", user.getUserCode());
                    }
                    if(action.getTaskReceiveTime()==null){//未接收
                        dcSupBacklogService.addOffice("督查督办","定时任务推送","反馈逾期提醒","提示信息"
                                ,"您有一条任务名为：'"+action.getTaskTitle()+"'的任务反馈即将逾期,请及时反馈!"
                                ,"/a/audit/taskReceive/list",action.getLeaderOrgCode()
                                ,action.getId(),"task_yuqi",userByOrg
                                ,action.getTaskId(),action.getId());
                    }else{
                        dcSupBacklogService.addOffice("督查督办","定时任务推送","反馈逾期提醒","提示信息"
                                ,"您有一条任务名为：'"+action.getTaskTitle()+"'的任务反馈即将逾期,请及时反馈!"
                                ,"/a/audit/taskReceive/list1",action.getLeaderOrgCode()
                                ,action.getId(),"task_yuqi",userByOrg
                                ,action.getTaskId(),action.getId());
                    }

                }

            }
        }

    }

    private List<EmpUser> findEmpUser(String code) {
        EmpUser empUser = new EmpUser();
        empUser.getEmployee().getOffice().setIsQueryChildren(true);
        empUser.getEmployee().getCompany().setIsQueryChildren(true);
        empUser.getEmployee().getOffice().setOfficeCode(code);
        empUser.setRoleCode("OTSLEADERESOLVE");
        List<EmpUser> userList = empUserService.findList(empUser);
        return userList;
    }

    private Map<String,String> createMsgDetail(DcSupTaskFeedback feedback, String phone) {
        String msg = "您好，您有一条反馈任务即将逾期请及时处理任务标题为：" + feedback.getTaskTitle();
        HashMap<String, String> map = new HashMap<>();
        map.put("context",msg);
        map.put("phone",phone);
        return map;
    }
}
